import 'dart:developer' as developer;

import 'package:azring/pages/sleep/sleep_logic.dart';
import 'package:flutter_native_splash/flutter_native_splash.dart';
import 'package:get/get.dart';
import 'status_state.dart';
import '../../core/controllers/ring_controller.dart';
import 'dart:async'; // Added for Timer
import 'dart:io';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import '../../core/repository/default_api.dart';
import '../../entity/food_record.dart';
import '../../core/models/ring_sport_record.dart';
import '../../core/models/sport_record.dart';
import '../../services/ring_service.dart';
import '../../services/device_storage_service.dart';
import '../../services/device_sn_manager.dart';

/// 状态页控制器
class StatusLogic extends GetxController {
  /// 状态实例
  final StatusState state = StatusState();

  // 获取戒指控制器
  RingController get ringController => Get.find<RingController>();

  // 防抖定时器
  Timer? _refreshDebounceTimer;
  bool _isRefreshing = false;

  // 滚动控制器
  final ScrollController scrollController = ScrollController();

  // 双击检测相关
  DateTime? _lastTapTime;
  static const Duration _doubleTapTimeout = Duration(milliseconds: 300);

  @override
  void onInit() {
    super.onInit();
    // 移除开屏页
    FlutterNativeSplash.remove();
      _loadStutusScore();//日历分数

    // 初始化逻辑
    _initializeDailyNutrition();

    _loadCardData();
    // 监听日期选择变化
    _setupDateSelectionListener();
    
    // 设置测量完成监听器
    _setupMeasurementListeners();
  }
  
  /// 设置测量完成监听器
  void _setupMeasurementListeners() {
    // 监听心率数据变化
    ever(ringController.heartRateDataRx, (heartRateData) {
      if (heartRateData != null && heartRateData.heartRate > 0 && ringController.isHeartRateMeasuring) {
        print('💓 检测到心率数据更新: ${heartRateData.heartRate} BPM，准备自动提交');
        // 延迟一点时间确保数据稳定
        Future.delayed(const Duration(milliseconds: 500), () {
          if (ringController.isHeartRateMeasuring) {
            _autoStopAndSubmitHeartRate();
          }
        });
      }
    });
    
    // 监听HRV数据变化
    ever(ringController.hrvDataRx, (hrvData) {
      if (hrvData != null && hrvData.hrv > 0 && ringController.isHrvMeasuring) {
        print('🫀 检测到HRV数据更新: ${hrvData.hrv} ms，准备自动提交');
        Future.delayed(const Duration(milliseconds: 500), () {
          if (ringController.isHrvMeasuring) {
            _autoStopAndSubmitHrv();
          }
        });
      }
    });
    
    // 监听血氧数据变化
    ever(ringController.bloodOxygenDataRx, (bloodOxygenData) {
      if (bloodOxygenData != null && bloodOxygenData.bloodOxygen > 0 && ringController.isBloodOxygenMeasuring) {
        print('🩸 检测到血氧数据更新: ${bloodOxygenData.bloodOxygen}%，准备自动提交');
        Future.delayed(const Duration(milliseconds: 500), () {
          if (ringController.isBloodOxygenMeasuring) {
            _autoStopAndSubmitBloodOxygen();
          }
        });
      }
    });
  }
  
  /// 自动停止并提交心率数据
  Future<void> _autoStopAndSubmitHeartRate() async {
    try {
      print('💓 自动停止心率测量并提交数据');
      await ringController.stopHeartRateMeasure();
      await _submitHeartRateData();
    } catch (e) {
      print('❌ 自动停止心率测量异常: $e');
    }
  }
  
  /// 自动停止并提交HRV数据
  Future<void> _autoStopAndSubmitHrv() async {
    try {
      print('🫀 自动停止HRV测量并提交数据');
      await ringController.stopHrvMeasure();
      await _submitHrvData();
    } catch (e) {
      print('❌ 自动停止HRV测量异常: $e');
    }
  }
  
  /// 自动停止并提交血氧数据
  Future<void> _autoStopAndSubmitBloodOxygen() async {
    try {
      print('🩸 自动停止血氧测量并提交数据');
      await ringController.stopBloodOxygenMeasure();
      await _submitBloodOxygenData();
    } catch (e) {
      print('❌ 自动停止血氧测量异常: $e');
    }
  }

  

  @override
  void onReady() {
    super.onReady();

    // 模块布局配置
    _loadModuleLayout();

    // 加载用餐类型
    _loadMealTypes();
  }

  /// 初始化当日营养数据（可以从本地存储或服务器获取）
  void _initializeDailyNutrition() {
    // 重置营养数据
    state.resetDailyNutrition();
  }

  /// 加载饮食记录列表
  Future<void> _loadFoodRecordList(String dateStr) async {
    try {
      final dynamic apiData =
          await DefaultApi().queryFoodInfoListGet<dynamic>(dailyValue: dateStr);

      // 直接返回列表的情况
      final List<FoodRecord> foodRecords = [];
      for (int i = 0; i < apiData['data'].length; i++) {
        try {
          final item = apiData['data'][i];
          final record = FoodRecord.fromMap(item as Map<String, dynamic>);
          foodRecords.add(record);
        } catch (e) {
          print('❌ 解析第${i + 1}条记录失败: $e');
        }
      }
      state.setFoodRecordList(foodRecords);
    } catch (e) {
      print('❌ API请求失败: $e');
    }
  }

  /// 刷新饮食记录列表（公开方法，供外部调用）
  Future<void> refreshFoodRecords() async {
    final targetDate = state.selectedDate.value;
    final dateStr =
        '${targetDate.year}-${targetDate.month.toString().padLeft(2, '0')}-${targetDate.day.toString().padLeft(2, '0')}';
    await _loadFoodRecordList(dateStr);
    // 同时刷新身体状况评分数据
    await _loadConditionScoreData(dateStr);
    print('✅ StatusController: 饮食记录和身体状况评分数据已刷新');
  }

  @override
  void onClose() {
    super.onClose();
    // 清理资源
    _refreshDebounceTimer?.cancel();
    scrollController.dispose();
  }

  /// 切换底部导航栏
  void changeTabIndex(int index) {
    // 检测双击状态页图标
    if (index == 0 && state.currentIndex.value == 0) {
      final now = DateTime.now();
      if (_lastTapTime != null &&
          now.difference(_lastTapTime!) < _doubleTapTimeout) {
        // 双击检测成功，滚动到顶部
        scrollToTop();
        _lastTapTime = null; // 重置
        return;
      }
      _lastTapTime = now;
    } else {
      _lastTapTime = null; // 切换到其他页面时重置
    }

    state.currentIndex.value = index;

    // todo://根据不同的页面索引执行相应的数据查询

    switch (index) {
      case 0: // 状态页
        // _loadCardData();

        break;
      case 1: // 睡眠页
        // 查询睡眠相关的所有数据
        // final sleepLogic = Get.find<SleepLogic>();
        // sleepLogic.refreshSleepDetailData();
        break;
      case 2: // 洞察页
        // 可以在这里添加洞察页的数据查询逻辑
        break;
      case 3: // 行动页
        // 可以在这里添加行动页的数据查询逻辑
        break;
      case 4: // 个人页
        // 可以在这里添加个人页的数据查询逻辑
        break;
    }
  }

  /// 滚动到顶部
  void scrollToTop() {
    if (scrollController.hasClients) {
      scrollController.animateTo(
        0,
        duration: const Duration(milliseconds: 500),
        curve: Curves.easeInOut,
      );
      print('📜 滚动到顶部');
    }
  }

  /// 开始心率测量
  Future<void> startHeartRateMeasurement() async {
    try {
      print('💓 开始心率测量');
      await ringController.startHeartRateMeasure();
      Toast.show('开始心率测量');
    } catch (e) {
      print('❌ 心率测量启动异常: $e');
      Toast.show('心率测量启动失败');
    }
  }

  /// 停止心率测量（手动停止，不自动提交）
  Future<void> stopHeartRateMeasurement() async {
    try {
      print('⏹️ 手动停止心率测量');
      await ringController.stopHeartRateMeasure();
      Toast.show('已停止心率测量');
    } catch (e) {
      print('❌ 停止心率测量异常: $e');
      Toast.show('停止心率测量失败');
    }
  }

  /// 提交心率数据到服务器
  Future<void> _submitHeartRateData() async {
    try {
      final heartRate = ringController.heartRate;
      if (heartRate <= 0 || heartRate > 300) {
        print('❌ 心率数据无效 ($heartRate BPM)，跳过提交');
        return;
      }

      final deviceSn = ringController.getCurrentDeviceSn();
      if (deviceSn.isEmpty) {
        print('❌ 设备序列号为空，无法提交心率数据');
        return;
      }

      final now = DateTime.now();
      final dailyValue =
          '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}';

      print('📤 提交心率数据: $heartRate BPM, 设备: $deviceSn, 日期: $dailyValue');

      await DefaultApi().addHeartRatePost<dynamic>(
        heartRate: heartRate.toString(),
        deviceSn: deviceSn,
        dailyValue: dailyValue,
        isShowErrMsg: false,
        isShowLoading: false,
      );

      print('✅ 心率数据提交成功');
      Toast.show('心率数据已上传 ($heartRate BPM)');
      
      // 跳转到心率详情页
      Get.toNamed('/heart-rate');
    } catch (e) {
      print('❌ 心率数据提交失败: $e');
      Toast.show('心率数据上传失败');
    }
  }

  /// 开始血氧测量
  Future<void> startBloodOxygenMeasurement() async {
    try {
      print('🩸 开始血氧测量');
      await ringController.startBloodOxygenMeasure();
      Toast.show('开始血氧测量');
    } catch (e) {
      print('❌ 血氧测量启动异常: $e');
      Toast.show('血氧测量启动失败');
    }
  }

  /// 停止血氧测量（手动停止，不自动提交）
  Future<void> stopBloodOxygenMeasurement() async {
    try {
      print('⏹️ 手动停止血氧测量');
      await ringController.stopBloodOxygenMeasure();
      Toast.show('已停止血氧测量');
    } catch (e) {
      print('❌ 停止血氧测量异常: $e');
      Toast.show('停止血氧测量失败');
    }
  }

  /// 提交血氧数据到服务器
  Future<void> _submitBloodOxygenData() async {
    try {
      final bloodOxygenData = ringController.bloodOxygenData;
      if (bloodOxygenData == null ||
          bloodOxygenData.bloodOxygen <= 0 ||
          bloodOxygenData.bloodOxygen > 100) {
        return;
      }
      final deviceSn = ringController.getCurrentDeviceSn();
      print('📤 提交血氧数据: ${bloodOxygenData.bloodOxygen}%, 设备: $deviceSn');

      await DefaultApi().addBloodOxygenDetailPost<dynamic>(
        bloodOxygen: bloodOxygenData.bloodOxygen.toString(),
        deviceSn: deviceSn,
        isShowErrMsg: false,
        isShowLoading: false,
      );
      print('✅ 血氧数据提交成功');
      Toast.show('血氧数据已上传 (${bloodOxygenData.bloodOxygen}%)');
      
      // 跳转到血氧详情页
      Get.toNamed('/blood-oxygen');
    } catch (e) {
      print('❌ 血氧数据提交失败: $e');
      Toast.show('血氧数据上传失败');
    }
  }

  /// 开始HRV测量
  Future<void> startHrvMeasurement() async {
    try {
      print('🫀 开始HRV测量');
      await ringController.startHrvMeasure();
      Toast.show('开始HRV测量');
    } catch (e) {
      print('❌ HRV测量启动异常: $e');
      Toast.show('HRV测量启动失败');
    }
  }

  /// 停止HRV测量（手动停止，不自动提交）
  Future<void> stopHrvMeasurement() async {
    try {
      print('⏹️ 手动停止HRV测量');
      await ringController.stopHrvMeasure();
      Toast.show('已停止HRV测量');
    } catch (e) {
      print('❌ 停止HRV测量异常: $e');
      Toast.show('停止HRV测量失败');
    }
  }

  /// 提交HRV数据到服务器
  Future<void> _submitHrvData() async {
    try {
      final hrvData = ringController.hrvData;
      if (hrvData == null || hrvData.hrv <= 0 || hrvData.hrv > 1000) {
        print('❌ HRV数据无效 (${hrvData?.hrv}ms)，跳过提交');
        return;
      }

      final deviceSn = ringController.getCurrentDeviceSn();
      if (deviceSn.isEmpty) {
        print('❌ 设备序列号为空，无法提交HRV数据');
        return;
      }

      final now = DateTime.now();
      final dailyValue =
          '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}';

      print('📤 提交HRV数据: ${hrvData.hrv}ms, 设备: $deviceSn, 日期: $dailyValue');

      await DefaultApi().addHrvPost<dynamic>(
        hrv: hrvData.hrv.toString(),
        deviceSn: deviceSn,
        dailyValue: dailyValue,
        isShowErrMsg: false,
        isShowLoading: false,
      );

      print('✅ HRV数据提交成功');
      Toast.show('HRV数据已上传 (${hrvData.hrv}ms)');
      
      // 跳转到心率变异性详情页
      Get.toNamed('/heart-rate/variability');
    } catch (e) {
      print('❌ HRV数据提交失败: $e');
      Toast.show('HRV数据上传失败');
    }
  }

  /// 查询心率数据
  Future<void> queryHeartRateData() async {
    try {
      print('💓 查询心率数据');
      await ringController.fetchHeartRateData();
    } catch (e) {
      print('❌ 心率数据查询异常: $e');
      Toast.show('心率数据查询失败');
    }
  }

  /// 查询血氧数据
  Future<void> queryBloodOxygenData() async {
    try {
      print('🩸 查询血氧数据');
      await ringController.fetchBloodOxygenData();
    } catch (e) {
      print('❌ 血氧数据查询异常: $e');
      Toast.show('血氧数据查询失败');
    }
  }

  /// 查询HRV数据
  Future<void> queryHrvData() async {
    try {
      print('🫀 查询HRV数据');
      await ringController.fetchHrvData();
    } catch (e) {
      print('❌ HRV数据查询异常: $e');
      Toast.show('HRV数据查询失败');
    }
  }

  /// 开始压力测量
  Future<void> startStressMeasurement() async {
    try {
      print('😰 开始压力测量');
      await ringController.startStressMeasure();
      Toast.show('开始压力测量');
    } catch (e) {
      print('❌ 压力测量启动异常: $e');
      Toast.show('压力测量失败');
    }
  }

  /// 停止压力测量
  Future<void> stopStressMeasurement() async {
    try {
      print('⏹️ 停止压力测量');
      await ringController.stopStressMeasure();
      Toast.show('已停止压力测量');
    } catch (e) {
      Toast.show('停止压力测量失败');
    }
  }

  /// 查询压力数据
  Future<void> queryStressData() async {
    try {
      print('😰 查询压力数据');
      await ringController.fetchStressData();
    } catch (e) {
      print('❌ 压力数据查询异常: $e');
      Toast.show('压力数据查询失败');
    }
  }

  /// 同步时间到设备
  Future<void> syncTimeToDevice() async {
    try {
      print('⏰ 同步时间到设备');
      await ringController.syncTime();
    } catch (e) {
      print('❌ 时间同步异常: $e');
      Toast.show('时间同步失败');
    }
  }

  /// 获取所有健康数据
  Future<void> fetchAllHealthData() async {
    try {
      print('📊 获取所有健康数据');
      if (!ringController.isConnected) {
        Toast.show('设备未连接');
        return;
      }

      // 获取所有数据
      await ringController.fetchAllData();
    } catch (e) {
      print('❌ 获取健康数据异常: $e');
      Toast.show('获取健康数据失败');
    }
  }

  /// 选择图片并上传（相机/相册）
  Future<void> pickAndUploadImage(
      {required bool isCamera,
      DateTime? selectedDate,
      String? mealType,
      String? description}) async {
    final ImagePicker picker = ImagePicker();
    try {
      if (isCamera) {
        final PermissionStatus status = await Permission.camera.request();
        if (!status.isGranted) {
          Toast.show('未获得相机权限');
          return;
        }
      } else {
        final bool ok = await _requestGalleryPermissions();
        if (!ok) {
          Toast.show('未获得相册权限');
          return;
        }
      }
      final XFile? xfile = await picker.pickImage(
        source: isCamera ? ImageSource.camera : ImageSource.gallery,
        imageQuality: 90,
        maxWidth: 2048,
      );
      if (xfile == null) {
        return;
      }
      final File file = File(xfile.path);
      final deviceSn = _getDeviceSn();
      final dynamic apiData = await DefaultApi().addFoodInfoPost<dynamic>(
        deviceSn: deviceSn,
        mealType: mealType ?? "1",
        file: file,
        description: description,
        isShowLoading: true,
      );
      if (apiData['code'] == 200) {
        final foodRecord = FoodRecord.fromMap(apiData);
        // 更新营养数据
        state.updateNutritionData(foodRecord);
        // 重新加载列表以确保数据同步
        final targetDate = state.selectedDate.value;
        final dateStr =
            '${targetDate.year}-${targetDate.month.toString().padLeft(2, '0')}-${targetDate.day.toString().padLeft(2, '0')}';
        await _loadFoodRecordList(dateStr);
        // 刷新身体状况评分数据
        await _loadConditionScoreData(dateStr);
      }
      Toast.show('饮食图片已上传');
    } catch (e) {
      Toast.show('图片上传失败');
    }
  }

  Future<bool> _requestGalleryPermissions() async {
    if (Platform.isAndroid) {
      final Map<Permission, PermissionStatus> statuses = await [
        Permission.photos, // Android 13+ 映射为 READ_MEDIA_IMAGES
        Permission.storage, // 低版本存储权限
      ].request();
      return statuses.values.any((s) => s.isGranted);
    }
    if (Platform.isIOS) {
      final PermissionStatus status = await Permission.photos.request();
      return status.isGranted;
    }
    return true;
  }

  /// 加载今日事件小计
  Future<void> _loadDailyEventsSummary(String dateStr) async {
    try {
      print('📝 StatusController: 开始加载今日事件小计');

      state.isLoadingDailyEvents.value = true;

      // 获取当前日期，格式为YYYY-MM-DD
      final now = DateTime.now();
      final dateStr =
          '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}';

      final response = await DefaultApi().getDailyTagsListGet<dynamic>(
        dailyValue: dateStr,
        isShowLoading: false,
        isShowErrMsg: false,
      );

      if (response != null) {
        List<DailyEventSummary> events = [];

        // 检查响应结构
        if (response is Map<String, dynamic>) {
          final code = response['code'];
          if (code == 200) {
            final data = response['data'];
            if (data != null && data is List && data.isNotEmpty) {
              for (var item in data) {
                if (item != null && item is Map<String, dynamic>) {
                  try {
                    events.add(DailyEventSummary.fromJson(item));
                  } catch (e) {
                    print('❌ 解析事件小计项目失败: $e, 数据: $item');
                  }
                }
              }
            } else if (data != null && data is Map<String, dynamic>) {
              // 单个事件的情况
              try {
                events.add(DailyEventSummary.fromJson(data));
              } catch (e) {
                print('❌ 解析单个事件小计失败: $e, 数据: $data');
              }
            }

            // 更新状态 - 不管是否有数据都更新，UI层会根据空列表显示介绍文字
            state.updateDailyEventsList(events);
            print('今日事件小计加载成功，共${events.length}条记录');
          } else {
            print('今日事件小计接口返回错误码: $code');
            state.updateDailyEventsList([]);
          }
        } else {
          print(' 今日事件小计接口返回数据格式异常: ${response.runtimeType}');
          state.updateDailyEventsList([]);
        }
      } else {
        print('今日事件小计接口返回null');
        // 接口异常时设置空数据，显示介绍文字
        state.updateDailyEventsList([]);
      }
    } catch (e) {
      print('加载今日事件小计失败: $e');

      // 出错时设置空数据，显示介绍文字
      state.updateDailyEventsList([]);
    } finally {
      state.isLoadingDailyEvents.value = false;
    }
  }

  /// 刷新今日事件小计
  Future<void> refreshDailyEventsSummary() async {
    final targetDate = state.selectedDate.value;
    final dateStr =
        '${targetDate.year}-${targetDate.month.toString().padLeft(2, '0')}-${targetDate.day.toString().padLeft(2, '0')}';
    await _loadDailyEventsSummary(dateStr);
    // 同时刷新身体状况评分数据
    await _loadConditionScoreData(dateStr);
  }

  /// 添加文字饮食记录
  Future<void> addTextFoodRecord(
      String description, DateTime selectedDate, String mealTime) async {
    try {
      print('📝 添加文字饮食记录: $description, 日期: $selectedDate, 时段: $mealTime');

      Toast.show('饮食记录已添加');

      // 重新加载饮食记录列表
      final dateStr =
          '${selectedDate.year}-${selectedDate.month.toString().padLeft(2, '0')}-${selectedDate.day.toString().padLeft(2, '0')}';
      await _loadFoodRecordList(dateStr);
      // 刷新身体状况评分数据
      await _loadConditionScoreData(dateStr);
      print('✅ StatusController: 饮食记录和身体状况评分数据已刷新');
    } catch (e) {
      Toast.show('添加饮食记录失败');
    }
  }

  /// 加载模块布局配置
  Future<void> _loadModuleLayout() async {
    try {
      print('📐 StatusController: 开始加载模块布局配置');
      state.isLoadingLayout.value = true;

      final response = await DefaultApi().queryLayoutListGet<dynamic>(
        isShowLoading: false,
        isShowErrMsg: false,
      );

      if (response != null && response['code'] == 200) {
        final data = response['data'];
        if (data != null && data is List) {
          final List<ModuleLayoutConfig> layouts = [];
          for (var item in data) {
            if (item != null && item is Map<String, dynamic>) {
              try {
                layouts.add(ModuleLayoutConfig.fromJson(item));
              } catch (e) {
                print('❌ 解析模块布局配置失败: $e, 数据: $item');
              }
            }
          }
          state.updateModuleLayout(layouts);
        }
      }
    } catch (e) {
      print('加载模块布局配置失败: $e');
    } finally {
      state.isLoadingLayout.value = false;
    }
  }

  /// 刷新模块布局配置（从编辑页面返回时调用）
  Future<void> refreshModuleLayout() async {
    await _loadModuleLayout();
  }

  /// 设置日期选择监听器
  void _setupDateSelectionListener() {
    // 监听日期变化，当用户点击日历选择日期时重新加载卡片数据
    ever(state.selectedDate, (DateTime selectedDate) {
      print('📅 StatusController: 检测到日期变化: $selectedDate');
      _loadCardData(date: selectedDate);
    });
  }

  /// 加载所有卡片数据
  Future<void> _loadCardData({DateTime? date}) async {
    // 获取设备序列号
    final deviceSn = _getDeviceSn();
    print(
        '📱 StatusController: 获取到的设备SN: ${deviceSn.isEmpty ? "空" : deviceSn}');

    if (deviceSn.isEmpty) {
      print('⚠️ StatusController: 无法获取设备序列号，跳过卡片数据加载');
      return;
    }

    // 使用传入的日期或当前选中的日期
    final targetDate = date ?? state.selectedDate.value;
    final dateStr =
        '${targetDate.year}-${targetDate.month.toString().padLeft(2, '0')}-${targetDate.day.toString().padLeft(2, '0')}';

    print('📅 StatusController: 查询日期: $dateStr');
    // 并行加载所有卡片数据
    await Future.wait([
      // 饮食记录
      _loadFoodRecordList(dateStr),

      // 加载今日事件小计
      _loadDailyEventsSummary(dateStr),
      _loadHeartRateCardData(dateStr), //心率
      _loadHrvCardData(dateStr), //心率变异性
      _loadSleepCardData(dateStr), //睡眠
      _loadSleepBloodOxygenData(dateStr), //血氧
      _loadExerciseRecordData(dateStr), //锻炼记录
      _loadMestrualCycle(dateStr), //生理周期
      _loadEmotionalInfoData(dateStr), // 加载压力情绪数据
      _loadDashboardData(dateStr), // 加载看板数据
      _loadConditionScoreData(dateStr), // 加载身体状况评分数据
      _loadActivityData(dateStr), // 加载活动数据
    ]);
    print('✅ StatusController: 所有卡片数据加载完成');
  }

  Future<void> _loadStutusScore() async {
    try {
      final deviceSn = _getDeviceSn();
      final res = await DefaultApi().queryRingTodaySignListGet<dynamic>(
        deviceSn: deviceSn,
      );

      if (res['data'] != null && res['data'] is List) {
        final List<dynamic> dataList = res['data'] as List<dynamic>;
        
        // 清空之前的数据
        state.statusScoreMap.clear();
        
        // 遍历数据，提取日期和分数
        for (var item in dataList) {
          if (item is Map<String, dynamic>) {
            final dailyValue = item['dailyValue']?.toString();
            final statusScore = item['statusScore'];
            
            if (dailyValue != null && statusScore != null) {
              state.statusScoreMap[dailyValue] = statusScore as int;
            }
          }
        }
        
        print('📊 StatusLogic: 加载状态评分数据 - 共 ${state.statusScoreMap.length} 条');
      }
    } catch (e) {
      print('❌ StatusLogic: 状态评分数据加载异常 - $e');
    }
  }

  Future<void> _loadMestrualCycle(String dateStr) async {
    try {
      final deviceSn = _getDeviceSn();
      final res = await DefaultApi().queryMenstrualCycleGet<dynamic>(
        dailyValue: dateStr,
        deviceSn: deviceSn.isNotEmpty ? deviceSn : null,
      );

      if (res['code'] == 200 && res['data'] != null) {
        final data =
            MenstrualCycleData.fromJson(res['data'] as Map<String, dynamic>);
        state.updateMenstrualCycleData(data);
      } else {}
    } catch (e) {
      print('生理周期数据加载异常 - $e');
    }
  }

  /// 获取设备序列号
  String _getDeviceSn() {
    try {
      final deviceSnManager = Get.find<DeviceSnManager>();
      return deviceSnManager.getDeviceSn();
    } catch (e) {
      developer.log('⚠️ 无法获取DeviceSnManager: $e', name: 'StatusLogic');
      return '';
    }
  }

  /// 加载心率卡片数据
  Future<void> _loadHeartRateCardData(String dateStr) async {
    print('💓 StatusLogic: 开始加载心率卡片数据，日期: $dateStr');
    try {
      final deviceSn = _getDeviceSn();
      print('💓 StatusLogic: 设备SN: $deviceSn');

      final response = await DefaultApi().queryHeartRateInfoGet<dynamic>(
        deviceSn: deviceSn.isNotEmpty ? deviceSn : null,
        dailyValue: dateStr,
        isShowLoading: false,
        isShowErrMsg: false,
      );

      print('💓 StatusLogic: API响应: ${response != null ? "成功" : "失败"}');

      if (response != null && response['code'] == 200) {
        final data = response['data'];
        print('💓 StatusLogic: 响应数据: $data');

        if (data != null) {
          final average = data['averageValue'] ?? 0;
          final startTime = data['startTime']?.toString() ?? '';
          final endTime = data['endTime']?.toString() ?? '';

          print(
              '💓 StatusLogic: API返回的睡眠时间 - startTime: "$startTime", endTime: "$endTime"');

          final List<HeartRatePoint> heartRateList = [];

          if (data['heartRateList'] != null && data['heartRateList'] is List) {
            for (var item in data['heartRateList']) {
              if (item != null && item is Map<String, dynamic>) {
                heartRateList.add(HeartRatePoint.fromJson(item));
              }
            }
          }

          state.updateHeartRateCardData(average, heartRateList,
              startTime: startTime, endTime: endTime);
          print(
              '💓 StatusLogic: 更新后的状态 - startTime: "${state.heartRateStartTime.value}", endTime: "${state.heartRateEndTime.value}"');
        }
      } else {
        print('💓 StatusLogic: API返回错误或code不是200');
      }
    } catch (e) {
      print('❌ StatusController: 加载心率卡片数据失败: $e');
    }
  }

  /// 加载HRV卡片数据
  Future<void> _loadHrvCardData(String dateStr) async {
    try {
      print('🫀 StatusController: 开始加载HRV卡片数据，日期: $dateStr');

      final deviceSn = _getDeviceSn();
      final response = await DefaultApi().queryRingHrvInfoGet<dynamic>(
        deviceSn: deviceSn.isNotEmpty ? deviceSn : null,
        historyDay: dateStr,
        isShowLoading: false,
        isShowErrMsg: false,
      );

      if (response != null && response['code'] == 200) {
        final data = response['data'];
        if (data != null) {
          final average = data['averageValue'] ?? 0;
          final List<HrvPoint> hrvList = [];

          if (data['hrvList'] != null && data['hrvList'] is List) {
            for (var item in data['hrvList']) {
              if (item != null && item is Map<String, dynamic>) {
                hrvList.add(HrvPoint.fromJson(item));
              }
            }
          }

          state.updateHrvCardData(average, hrvList);
          print('✅ StatusController: HRV卡片数据加载成功');
        }
      }
    } catch (e) {
      print('❌ StatusController: 加载HRV卡片数据失败: $e');
    }
  }

  /// 加载睡眠卡片数据
  Future<void> _loadSleepCardData(String dateStr) async {
    try {
      print('😴 StatusController: 开始加载睡眠卡片数据，日期: $dateStr');

      final deviceSn = _getDeviceSn();
      final response = await DefaultApi().querySleepInfoGet<dynamic>(
        deviceSn: deviceSn.isNotEmpty ? deviceSn : null,
        dailyValue: dateStr,
        type:"1",
        isShowLoading: false,
        isShowErrMsg: false,
      );

      if (response != null && response['code'] == 200) {
        final data = response['data'];
        if (data != null) {
          final sleepData = SleepCardData.fromJson(data);
          state.updateSleepCardData(sleepData);
          print('✅ StatusController: 睡眠卡片数据加载成功');
        }
      }
    } catch (e) {
      print('❌ StatusController: 加载睡眠卡片数据失败: $e');
    }
  }

  /// 加载睡眠血氧数据
  Future<void> _loadSleepBloodOxygenData(String dateStr) async {
    try {
      print('🩸 StatusController: 开始加载睡眠血氧数据，日期: $dateStr');

      final deviceSn = _getDeviceSn();
      final response = await DefaultApi().querySleepBloodOxygenGet<dynamic>(
        deviceSn: deviceSn.isNotEmpty ? deviceSn : null,
        dailyValue: dateStr,
        isShowLoading: false,
        isShowErrMsg: false,
      );

      if (response != null && response['code'] == 200) {
        final data = response['data'];
        if (data != null) {
          // 更新睡眠血氧数据
          final bloodOxygenData = SleepBloodOxygenData.fromJson(data);
          state.updateSleepBloodOxygenData(bloodOxygenData);

          // 同时更新血氧卡片数据（平均值和列表）
          final average = data['average'] ?? 0;
          final List<BloodOxygenPoint> bloodOxygenList = [];

          if (data['heartRateList'] != null && data['heartRateList'] is List) {
            for (var item in data['heartRateList']) {
              if (item != null && item is Map<String, dynamic>) {
                bloodOxygenList.add(BloodOxygenPoint.fromJson(item));
              }
            }
          }

          state.updateBloodOxygenCardData(average, bloodOxygenList);
        }
      }
    } catch (e) {
      print('❌ StatusController: 加载睡眠血氧数据失败: $e');
    }
  }

  /// 加载运动记录数据
  Future<void> _loadExerciseRecordData(String dateStr) async {
    try {
      print('🏃 StatusController: 开始加载运动记录数据，日期: $dateStr');

      final deviceSn = _getDeviceSn();
      final response = await DefaultApi().queryExerciseRecordsGet<dynamic>(
        deviceSn: deviceSn.isNotEmpty ? deviceSn : null,
        dailyValue: dateStr,
        isShowLoading: false,
        isShowErrMsg: false,
      );

      if (response != null && response['code'] == 200) {
        final data = response['data'];
        final exerciseData = data != null
            ? ExerciseRecordData.fromJson(data)
            : ExerciseRecordData(); // 使用空数据，UI层会显示 "--"
        state.updateExerciseRecordData(exerciseData);
        print('✅ StatusController: 运动记录数据加载成功');
      } else {
        // API返回失败，也更新为空数据
        state.updateExerciseRecordData(ExerciseRecordData());
      }
    } catch (e) {
      print('❌ StatusController: 加载运动记录数据失败: $e');
      // 异常情况也更新为空数据
      state.updateExerciseRecordData(ExerciseRecordData());
    }
  }

  /// 加载活动数据
  Future<void> _loadActivityData(String dateStr) async {
    try {
      print('🏃 StatusController: 开始加载活动数据，日期: $dateStr');

      final deviceSn = _getDeviceSn();
      final response = await DefaultApi().queryPhysicalActivitiesGet<dynamic>(
        deviceSn: deviceSn.isNotEmpty ? deviceSn : null,
        dailyValue: dateStr,
        isShowLoading: false,
        isShowErrMsg: false,
      );

      if (response != null && response['code'] == 200) {
        final data = response['data'];
        if (data != null) {
          final activityData = ActivityData.fromJson(data);
          state.updateActivityData(activityData);
        }
      }
    } catch (e) {
      print('❌ StatusController: 加载活动数据失败: $e');
    }
  }

  /// 刷新所有卡片数据（供外部调用）
  Future<void> refreshCardData() async {
    await _loadCardData(date: state.selectedDate.value);
  }

  /// 提交情绪状态到服务器
  Future<void> submitEmotionalState(int emotionalStateIndex) async {
    try {
      // 将情绪索引(0-4)映射为情绪状态(1-5)
      final int emotionalState = emotionalStateIndex + 1;

      // 获取当前设备的SN
      final deviceSn = ringController.getCurrentDeviceSn();

      if (deviceSn.isEmpty) {
        print('⚠️ 设备SN为空，尝试从存储中获取');
        // 如果当前没有连接，尝试从DeviceStorageService获取
        try {
          final deviceStorage = Get.find<DeviceStorageService>();
          final lastDevice = deviceStorage.lastConnectedDevice;
          if (lastDevice != null && lastDevice.deviceSn.isNotEmpty) {
            print('✅ 从存储中获取到设备SN: ${lastDevice.deviceSn}');
            await _submitEmotionalStateToApi(
                emotionalState, lastDevice.deviceSn);
            return;
          }
        } catch (e) {
          print('❌ 无法从存储中获取设备信息: $e');
        }

        Toast.show('无法获取设备信息，请先连接设备');
        return;
      }

      await _submitEmotionalStateToApi(emotionalState, deviceSn);
    } catch (e) {
      print('❌ 情绪状态提交失败: $e');
      Toast.show('情绪状态提交失败');
    }
  }

  /// 提交情绪状态到API
  Future<void> _submitEmotionalStateToApi(
      int emotionalState, String deviceSn) async {
    print('📤 提交情绪状态: $emotionalState, 设备SN: $deviceSn');

    await DefaultApi().addEmoionalInfoPost<dynamic>(
      emotionalState: emotionalState.toString(),
      deviceSn: deviceSn,
      isShowLoading: true,
    );

    print('✅ 情绪状态提交成功');
    Toast.show('情绪状态已记录');
  }

  /// 加载压力情绪数据
  Future<void> _loadEmotionalInfoData(String dateStr) async {
    try {
      print('📊 StatusController: 开始加载压力情绪数据，日期: $dateStr');

      final deviceSn = _getDeviceSn();
      print('📊 StatusController: 设备SN: $deviceSn');
      
      final response = await DefaultApi().queryEmotionalInfoStateGet<dynamic>(
        deviceSn: deviceSn.isNotEmpty ? deviceSn : null,
        dailyValue: dateStr,
        isShowLoading: false,
        isShowErrMsg: false,
      );

      print('📊 StatusController: API响应: ${response != null ? "成功" : "失败"}');
      
      if (response != null && response['code'] == 200) {
        final data = response['data'];
        print('📊 StatusController: 响应数据: $data');
        
        if (data != null) {
          // 更新平均压力值
          final average = data['average'] ?? 0;
          state.currentStress.value = average;
          print('📊 StatusController: 平均压力值: $average');

          // 更新情绪状态数据
          final emotionalState = data['emotionalState']?.toString() ?? '';
          final recordDate = data['recordDate']?.toString() ?? '';
          final weekName = data['weekName']?.toString() ?? '';
          final recordTime = data['recordTime']?.toString() ?? '';
          
          print('📊 StatusController: 情绪状态: $emotionalState, 日期: $recordDate, 时间: $recordTime');

          final List<EmotionalStateRecord> emotionalRecords = [];
          if (data['emotionalStateList'] != null &&
              data['emotionalStateList'] is List) {
            final list = data['emotionalStateList'] as List;
            print('📊 StatusController: 情绪记录列表长度: ${list.length}');
            
            for (var item in list) {
              if (item != null && item is Map<String, dynamic>) {
                final record = EmotionalStateRecord.fromJson(item);
                emotionalRecords.add(record);
                print('📊 StatusController: 情绪记录 - 状态: ${record.emotionalState}, 时间: ${record.recordTime}');
              }
            }
          }
          
          print('📊 StatusController: 解析后的情绪记录数量: ${emotionalRecords.length}');

          // 始终更新情绪状态数据，即使emotionalState为空
          state.updateEmotionalStateData(
            emotionalState: emotionalState,
            recordDate: recordDate,
            weekName: weekName,
            recordTime: recordTime,
            emotionalRecords: emotionalRecords,
          );

          // 更新压力列表数据
          final List<int?> stressChangeList = [];
          if (data['stressChangeInfoList'] != null &&
              data['stressChangeInfoList'] is List) {
            final list = data['stressChangeInfoList'] as List;
            print('📊 StatusController: 压力变化列表长度: ${list.length}');
            
            for (var item in list) {
              if (item != null && item is Map<String, dynamic>) {
                final value = item['value'];
                stressChangeList.add(value is int ? value : null);
              }
            }
          }

          print('📊 StatusController: 解析后的压力数据点数量: ${stressChangeList.length}');
          
          // 始终更新压力列表，即使为空
          state.updateTodayStressList(stressChangeList);
          print('✅ StatusController: 压力情绪数据加载成功，平均值: $average, 压力数据点: ${stressChangeList.length}, 情绪记录: ${emotionalRecords.length}');
        } else {
          print('⚠️ StatusController: API返回的data为null');
          // 清空数据
          state.updateTodayStressList([]);
          state.updateEmotionalStateData(
            emotionalState: '',
            recordDate: '',
            weekName: '',
            recordTime: '',
            emotionalRecords: [],
          );
        }
      } else {
        print('⚠️ StatusController: API返回失败或code不是200');
        // 清空数据
        state.updateTodayStressList([]);
        state.updateEmotionalStateData(
          emotionalState: '',
          recordDate: '',
          weekName: '',
          recordTime: '',
          emotionalRecords: [],
        );
      }
    } catch (e) {
      print('❌ StatusController: 加载压力情绪数据失败: $e');
      // 清空数据
      state.updateTodayStressList([]);
      state.updateEmotionalStateData(
        emotionalState: '',
        recordDate: '',
        weekName: '',
        recordTime: '',
        emotionalRecords: [],
      );
    }
  }

  /// 加载看板数据
  Future<void> _loadDashboardData(String dateStr) async {
    try {
      print('📊 StatusController: 开始加载看板数据，日期: $dateStr');

      final deviceSn = _getDeviceSn();
      final response = await DefaultApi().queryDashboardGet<dynamic>(
        deviceSn: deviceSn.isNotEmpty ? deviceSn : null,
        dailyValue: dateStr,
        isShowLoading: false,
        isShowErrMsg: false,
      );

      if (response != null && response['code'] == 200) {
        final data = response['data'];
        if (data != null) {
          final dashboardData = DashboardData.fromJson(data);
          state.updateDashboardData(dashboardData);
          print('✅ StatusController: 看板数据加载成功');
        }
      }
    } catch (e) {
      print('❌ StatusController: 加载看板数据失败: $e');
    }
  }

  /// 加载身体状况评分数据
  Future<void> _loadConditionScoreData(String dateStr) async {
    try {
      print('💯 StatusController: 开始加载身体状况评分数据，日期: $dateStr');

      final deviceSn = _getDeviceSn();
      final response = await DefaultApi().queryConditionScoreGet<dynamic>(
        deviceSn: deviceSn.isNotEmpty ? deviceSn : null,
        dailyValue: dateStr,
        isShowLoading: false,
        isShowErrMsg: false,
      );

      if (response != null && response['code'] == 200) {
        final data = response['data'];
        if (data != null) {
          final conditionScoreData = ConditionScoreData.fromJson(data);
          state.updateConditionScoreData(conditionScoreData);
          print(
              '✅ StatusController: 身体状况评分数据加载成功，总分: ${conditionScoreData.totalScore}');
        }
      }
    } catch (e) {
      print('❌ StatusController: 加载身体状况评分数据失败: $e');
    }
  }

  /// 加载用餐类型列表
  Future<void> _loadMealTypes() async {
    try {
      print('🍽️ StatusController: 开始加载用餐类型列表');
      state.isLoadingMealTypes.value = true;

      final response = await DefaultApi().dataTypeGet<dynamic>(
        dictType: 'az_meal_type',
        isShowErrMsg: false,
      );

      if (response != null) {
        List<MealTypeOption> mealTypes = [];

        // 处理响应数据
        if (response is Map<String, dynamic>) {
          final data = response['data'];
          if (data != null && data is List) {
            for (var item in data) {
              if (item != null && item is Map<String, dynamic>) {
                try {
                  mealTypes.add(MealTypeOption.fromJson(item));
                } catch (e) {
                  print('❌ 解析用餐类型失败: $e, 数据: $item');
                }
              }
            }
          }
        } else if (response is List) {
          for (var item in response) {
            if (item != null && item is Map<String, dynamic>) {
              try {
                mealTypes.add(MealTypeOption.fromJson(item));
              } catch (e) {
                print('❌ 解析用餐类型失败: $e, 数据: $item');
              }
            }
          }
        }

        state.updateMealTypeList(mealTypes);
        print('✅ StatusController: 用餐类型加载成功，共${mealTypes.length}个类型');
      }
    } catch (e) {
      print('❌ StatusController: 加载用餐类型失败: $e');
    } finally {
      state.isLoadingMealTypes.value = false;
    }
  }

  /// 刷新压力情绪数据（提交情绪后调用）
  Future<void> refreshEmotionalData() async {
    final targetDate = state.selectedDate.value;
    final dateStr =
        '${targetDate.year}-${targetDate.month.toString().padLeft(2, '0')}-${targetDate.day.toString().padLeft(2, '0')}';
    await _loadEmotionalInfoData(dateStr);
    print('✅ StatusController: 情绪数据已刷新，emoji应该显示在压力图表上');
  }

  /// 刷新身体状况评分数据（添加事件或饮食记录后调用）
  Future<void> refreshConditionScoreData() async {
    final targetDate = state.selectedDate.value;
    final dateStr =
        '${targetDate.year}-${targetDate.month.toString().padLeft(2, '0')}-${targetDate.day.toString().padLeft(2, '0')}';
    await _loadConditionScoreData(dateStr);
    print('✅ StatusController: 身体状况评分数据已刷新');
  }
}
